#!/bin/bash
# Simple comparison script for C and Fortran debug outputs

# Colors for output - disabled for plain text output
GREEN=""
RED=""
YELLOW=""
NC=""

# Read from stdin or file
input=$(cat)

# Automatically identify the two most frequent classnames by looking for lines with [classname] and norm=
echo "Detecting classnames in the log file..."
classnames=$(echo "$input" | grep "norm=" | grep -o "\[\w\+\]" | grep -v "DEBUG" | sort | uniq -c | sort -nr | head -2 | awk '{print $2}' | tr -d '[]')
class1=$(echo "$classnames" | head -1)
class2=$(echo "$classnames" | tail -1)

class1_count=$(echo "$input" | grep -c "\[$class1\].*norm=")
class2_count=$(echo "$input" | grep -c "\[$class2\].*norm=")

echo "Detected classnames: $class1 ($class1_count entries) and $class2 ($class2_count entries)"
echo ""

# Compare values using AWK for better tag normalization and matching
echo "$input" | awk -v class1="$class1" -v class2="$class2" '
BEGIN {
  printf "%-40s %-15s %-15s %-15s\n", "Tag", class1 " Value", class2 " Value", "Diff (%)";
  printf "%-40s %-15s %-15s %-15s\n", "----------------------------------------", "---------------", "---------------", "---------------";
  
  # Initialize arrays to store zero values properly
  all_tags[class1] = 0;
  all_tags[class2] = 0;
}

# Extract all debug entries with their normalized names
/^\[('"$class1"'|'"$class2"')\]/ {
  class = substr($1, 2, length($1)-2);
  tag = $2;
  
  # Extract step number
  match($0, /step=([0-9]+)/, step_arr);
  step = step_arr[1];
  
  # Extract norm value - improved to handle scientific notation
  if (match($0, /norm=[ ]*([0-9]*\.[0-9]+[Ee][\+\-]?[0-9]+|[0-9]*\.?[0-9]+)/, norm_arr)) {
    norm = norm_arr[1];
    
    # Normalize tag names between classes
    norm_tag = tag;
    # gsub("_domain", "", norm_tag);
    # Comment out or remove this line to keep _full tags:
    # gsub("_full", "", norm_tag);
    # gsub("south_polar_exchange", "south_exchange", norm_tag);
    
    # Store in array with normalized tag as key
    key = norm_tag "_step_" step;
    if (class == class1) {
      class1_values[key] = norm;
      all_tags[class1] = all_tags[class1] + 1;
    } else {
      class2_values[key] = norm;
      all_tags[class2] = all_tags[class2] + 1;
    }
    all_keys[key] = 1;
    
    # Store original tags for display
    if (!(key in orig_tags)) {
      orig_tags[key] = tag " (step=" step ")";
    }
  }
}

END {
  # Combine all unique tags from both classes
  for (key in all_keys) {
    if (!(key in class1_values)) {
      # Check if we need to set it to zero (tag exists in class2 but not class1)
      # We set it to 0.00000E+00 to match scientific notation
      class1_values[key] = "0.00000E+00";
    }
    if (!(key in class2_values)) {
      # Check if we need to set it to zero (tag exists in class1 but not class2)
      class2_values[key] = "0.00000E+00";
    }
  }
  
  # Print all entries with their matching pairs
  PROCINFO["sorted_in"] = "@ind_str_asc"; # Sort by keys alphabetically
  for (key in all_keys) {
    # Extract display tag using original tag if possible
    display = orig_tags[key];
    if (length(display) > 38) {
      display = substr(display, 1, 35) "...";
    }
    
    class1_val = class1_values[key];
    class2_val = class2_values[key];
    
    # Calculate difference percentage
    diff = "N/A";
    class1_num = class1_val + 0;  # Convert to numeric
    class2_num = class2_val + 0;  # Convert to numeric
    
    if (class1_num == 0 && class2_num == 0) {
      # Both are zero
      diff = "0.00000";
    } else if (class1_num == 0) {
      # If class1 is zero, diff is the value of class2
      diff = sprintf("%g", class2_num);
    } else if (class2_num == 0) {
      # If class2 is zero, diff is the negative value of class1
      diff = sprintf("-%g", class1_num);
    } else {
      # Normal percentage difference
      diff = (class2_num - class1_num) / class1_num * 100;
      diff = sprintf("%.5f", diff);
    }
    
    # Highlight significant differences
    if ((diff + 0) > 1 || (diff + 0) < -1) {
      diff = diff;  # In colored version, would add coloring here
    }
    
    printf "%-40s %-15s %-15s %-15s\n", display, class1_val, class2_val, diff;
  }
}'

# Extract DEBUG lines
class1_prefix="${class1:0:1}"
class2_prefix="${class2:0:1}"

debug1=$(echo "$input" | grep "\[DEBUG-$class1_prefix" | sort | uniq)
debug2=$(echo "$input" | grep "\[DEBUG-$class2_prefix" | sort | uniq)

if [[ -n "$debug1" || -n "$debug2" ]]; then
  echo -e "\nAdditional debug information:"
  if [[ -n "$debug1" ]]; then
    echo "$class1 Debug:"
    echo "$debug1"
    echo ""
  fi
  
  if [[ -n "$debug2" ]]; then
    echo "$class2 Debug:"
    echo "$debug2"
  fi
fi 